package com.kingbook.core.executor;

import com.kingbook.common.utils.StringUtils;
import com.kingbook.core.utils.JDBCHelper;
import org.springframework.jdbc.core.ResultSetExtractor;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Bucky
 * @Date: 2019/1/2
 * @Version 1.0
 */
class MapArrayResultSetExtractor implements ResultSetExtractor<Map<String, Object>[]> {


    @Override
    public Map<String, Object>[] extractData(ResultSet rs) throws SQLException {
        if (rs.last()) {
            int length = rs.getRow();
            HashMap<String, Object>[] maps = new HashMap[length];
            rs.beforeFirst();
            ResultSetMetaData rsm = rs.getMetaData();
            int columnCount = rsm.getColumnCount();
            HashMap<String, Object> zmap;
            for (int index = 0; rs.next(); index++) {
                zmap = new HashMap<String, Object>(columnCount);
                for (int i = 1; i <= columnCount; i++) {
                    zmap.put(StringUtils.toCamelCase(rsm.getColumnLabel(i)), JDBCHelper.getFormatResult(rs, i));
                }
                maps[index] = zmap;
            }
            return maps;
        }
        return new HashMap[0];
    }

}